import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {UrlService} from '../common/service/url.service';
import {Observable} from 'rxjs';
import {ApiRes} from '../common/model/response';
import {map} from 'rxjs/operators';
import {Page} from '../common/model/page';
import {SearchResult} from './model/search-result';

@Injectable({
  providedIn: 'root'
})
export class ContentService {

  constructor(private http: HttpClient,
              private urlService: UrlService) {
  }

// 获取地图json
  getGeoJson(jsonPath: string): Observable<any> {
    return this.http.get(jsonPath);
  }

  // 获取各省市的value
  getProvinceTips(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policyAnalysis/countPolicyWithRegionGroupYear');
    return this.http.get<ApiRes>(url).pipe(map(res => {
      // const dataTemp = [];
      // for (const item of res.result) {
      //   dataTemp.push({name: item.name, value: item.count});
      // }
      // res.result = dataTemp;
      return res;
    }));

  }

  // 获取所有年份
  getAllYears(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policyAnalysis/getPolicyAllYear');
    return this.http.get<ApiRes>(url);

  }

  // 获取发布机构列表
  getPublishOrgan(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policyAnalysis/countPolicyWithPublishOrgan');
    return this.http.get<ApiRes>(url);

  }

  // 获取政策扩散节点数据
  getCountSpread(condition: string): Observable<ApiRes> {
    const params = new HttpParams().append('province', condition);
    const url = this.urlService.getWebUrl('/policyAnalysis/countWithSpread');
    return this.http.get<ApiRes>(url, {params});

  }

  // 获取省市列表
  getProvinceList(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policyAnalysis/getPolicyAllProvince');
    return this.http.get<ApiRes>(url);

  }

  // 获取政策热点聚焦数据
  policyFocusData(condition: Page): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policyAnalysis/policyFocus');
    // @ts-ignore
    return this.http.get<ApiRes>(url, {params: condition});

  }

  // 获取合作机构发文数据
  policyPost(condition: string): Observable<ApiRes> {
    const params = new HttpParams().append('pageSize', condition);
    const url = this.urlService.getWebUrl('/policyAnalysis/countWithCooperation');
    return this.http.get<ApiRes>(url, {params});

  }

  // 获取政策矩阵第二行信息
  getWordFrameTopFour(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policyAnalysis/policyJz');
    return this.http.get<ApiRes>(url);

  }

  // -----不同区域科技创新体系内容对比分析----
  getMatrix(condition: any): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/jz/searchWebV2');
    return this.http.post<ApiRes>(url, condition);

  }

  getFrameList(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/policySearch/wordFreamList');
    return this.http.get<ApiRes>(url).pipe(map(res => {
      const tempResult = res.result;
      for (const frame of tempResult) {
        frame.checked = false;
      }
      res.result = tempResult;
      return res;
    }));

  }

  getRegion(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/jz/region');
    return this.http.get<ApiRes>(url).pipe(map(res => {
      res.result = this.formatRegion(res.result, false);
      return res;
    }));
  }

  getOrgans(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/jz/publishOrgan');
    return this.http.get<ApiRes>(url).pipe(map(res => {
      res.result = this.formatRegion(res.result);
      return res;
    }));
  }

  getFileList(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/jz/policyType');
    return this.http.get<ApiRes>(url);
  }

  getHotSpots(): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/jz/hotKeywords');
    return this.http.get<ApiRes>(url).pipe(map(res => {
      const list = [];
      for (const re of res.result) {
        const obj = {label: '', value: ''};
        obj.label = re;
        obj.value = re;
        list.push(obj);
      }
      res.result = list;
      return res;
    }));
  }

// 将对象数组格式化为树
  formatRegion(result: any, isRegion?: boolean) {
    if (isRegion) {
      const preObj = {
        国家自主创新示范区: ['北京', '武汉', '上海', '深圳', '南京', '苏州', '天津', '杭州', '广州', '珠海', '福州', '厦门', '合肥'],
        科技创新中心: ['北京', '上海', '广州', '深圳', '珠海'],
        综合性国家科学中心: ['上海', '合肥', '北京', '深圳']
      };
      result = Object.assign(preObj, result);
    }
    const option = [];
    for (const region in result) {
      const tree = {
        value: '',
        label: '',
        isLeaf: true,
        children: []
      };
      tree.value = region;
      tree.label = region;
      if (result.hasOwnProperty(region)) {
        const regionChild = result[region];
        if (regionChild.length) {
          tree.isLeaf = false;
          for (const child of regionChild) {
            const treeChild = {
              value: child,
              label: child,
              isLeaf: true,
              children: []
            };
            tree.children.push(treeChild);
          }
        }
      }
      option.push(tree);
    }
    return option;
  }

  searchByCondition(condition: any): Observable<ApiRes> {
    const url = this.urlService.getWebUrl('/jz/search');
    return this.http.post<ApiRes>(url, condition);
  }

  getTopKeyword(pageSize: number): Observable<ApiRes> {
    const params = new HttpParams().append('pageSize', String(pageSize));
    const url = this.urlService.getWebUrl('/policyAnalysis/countWithQuarterAndKeyword');
    return this.http.get<ApiRes>(url, {params}).pipe(map(res => {
      // 因为echarts对数据源的格式要求，在此将数据源格式化
      for (const year in res.result) {
        if (res.result.hasOwnProperty(year)) {
          const data = [];
          for (let i = 0; i < pageSize; i++) {
            const rowTemp = [];
            res.result[year].forEach((quarter: any[], index: number) => {
              rowTemp.push(quarter[i]);
            });
            data.push(rowTemp);
          }
          res.result[year] = data;
        }
      }
      return res;
    }));

  }
}
